import Vue from 'vue';
import VueRouter from 'vue-router';
import Login from '../views/Login.vue';
import Home from '../views/Home.vue';
import PublicActivities from '../views/PublicActivities.vue';
import ActivityDetail from '../views/ActivityDetail.vue';
import ActivityManagement from '../views/ActivityManagement.vue';
import HomeView from '../views/HomeView.vue';

Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    name: 'Login', // 根路径指向登录页面
    component: Login,
  },
  {
    path: '/home',
    name: 'Home',
    component: HomeView,
    meta: { requiresAuth: true }, // 需要登录
  },
  {
    path: '/public-activities',
    name: 'PublicActivities',
    component: PublicActivities,
    meta: { requiresAuth: true }, // 需要登录
  },
  {
    path: '/public-activities/:id',
    name: 'ActivityDetail',
    component: ActivityDetail,
    meta: { requiresAuth: true }, // 需要登录
  },
  {
    path: '/activity-management',
    name: 'ActivityManagement',
    component: ActivityManagement,
    meta: { requiresAdmin: true }, // 需要管理员权限
  },
];

const router = new VueRouter({
  mode: 'history',
  routes,
});

// 全局前置路由守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('isAuthenticated');
  const userRole = localStorage.getItem('userRole');

  // 检查是否需要登录
  if (to.meta.requiresAuth && !isAuthenticated) {
    next('/'); // 未登录时跳转到登录页
  } else if (to.meta.requiresAdmin && userRole !== 'admin') {
    // 检查是否为管理员
    alert('无权限访问');
    next('/'); // 非管理员跳转到首页
  } else {
    next(); // 允许访问
  }
});

export default router;